package main

import (
	"crypto/md5"
	"fmt"
	"html/template"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
	//"encoding/hex"
)

func sayHello(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Println(r.Form)
	fmt.Println("path", r.URL.Path)
	fmt.Println("scheme", r.URL.Scheme)

	for k, v := range r.Form {
		fmt.Println("key:", k)
		fmt.Println("val:", strings.Join(v, ""))
	}

	fmt.Fprintf(w, "Hello, World!")
}

func login(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Println("method:", r.Method, ", form: ", r.Form)
	if r.Method == "GET" {
		expiration := time.Now()
		expiration = expiration.AddDate(1, 0, 0)
		cookie := http.Cookie{Name: "username", Value: "astaxie", Expires: expiration}
		http.SetCookie(w, &cookie)

		t, _ := template.ParseFiles("login.html")
		log.Println(t.Execute(w, nil))
	} else {
		fmt.Println("username:", r.Form["username"])
		fmt.Println("password:", r.Form["password"])

		slice := []string{"apple", "pear", "banane"}
		value := r.Form.Get("fruit")
		for _, v := range slice {
			if v == value {
				fmt.Println("v:", v)
			}
		}
		cookie, _ := r.Cookie("username")
		fmt.Fprintf(w, "%v", cookie)
		log.Println("cookie:", cookie)
	}
}

func test(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Fprintf(w, "test!")

	//cookie, _ := r.Cookie("username")
	//fmt.Fprintf(w, "%v", cookie)
	//log.Println("cookie:", cookie)
	for _, cookie := range r.Cookies() {
		log.Println("cookie.name:", cookie.Name)
		log.Println("cookie:", cookie)
		log.Println("")
	}
}

func upload(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method)
	if r.Method == "GET" {
		//generate token start
		crutime := time.Now().Unix()
		log.Println("crutime : ", crutime)
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))
		//generate token end

		t, _ := template.ParseFiles("upload.html")
		temp := t.Execute(w, token)
		log.Println(temp)
	} else {
		r.ParseMultipartForm(32 << 20)
		file, handler, err := r.FormFile("uploadfile")
		if err != nil {
			log.Println("err: ", err)
			return
		}
		defer file.Close()

		fmt.Fprintf(w, "%v", handler.Header)
		fSave, err := os.OpenFile("./test/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			log.Println("err: ", err)
			return
		}
		defer fSave.Close()
		io.Copy(fSave, file)

	}
}

type Friend struct {
	Fname string
}

type Persion struct {
	UserName string
	Email    []string
	Friends  []*Friend
}

func testtemplate(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("testtemplate.html")
	f1 := Friend{Fname: "chen"}
	f2 := Friend{Fname: "chen2"}
	p := Persion{UserName: "Astaxie",
		Email:   []string{"langxianwen@163.com", "langxianwenye@163.com"},
		Friends: []*Friend{&f1, &f2}}
	log.Println(p.Friends[0])
	temp := t.Execute(w, p)
	log.Println(temp)
}

func main() {
	fmt.Println("Web start")
	http.HandleFunc("/", sayHello)
	http.HandleFunc("/login", login)
	http.HandleFunc("/test", test)
	http.HandleFunc("/upload", upload)
	http.HandleFunc("/testtemplate", testtemplate)
	//http.HandleFunc("/cookie", cookie)
	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		log.Fatal("langxw Listen and serve", err)
	} else {
		fmt.Println("Web ready")
	}
}
